<?php
/**
 * Created by PhpStorm.
 * User: wudiying
 * Date: 2020/2/20
 * Time: 上午12:18
 */

/**
 *
 * swoole之聊天的简单实现：
 * 服务器端代码：
 */

//创建websocket服务器
$ws = new swoole_websocket_server("0.0.0.0", 9502);

$ws->on('open', function ($ws, $request) {
    echo '新用户：' . $request->fd . '加入';
//设置用户id，存入全局变量
    $GLOBALS['fd'][$request->fd]['id'] = $request->fd;
    $GLOBALS['fd'][$request->fd]['name'] = '匿名用户';
});

$ws->on('message', function ($ws, $request) {
    $msg = $GLOBALS['fd'][$request->fd]['name'] . ":" . $request->data . "\n";
    if (strstr($request->data, "#name#")) {
//用户设置昵称
        $GLOBALS['fd'][$request->fd]['name'] = str_replace("#name#", '', $request->data);
    } else {
//发送给每一个客户端
        foreach ($GLOBALS['fd'] as $val) {
            $ws->push($val['id'], $msg);
        }
    }
});

$ws->on('close', function () {
    echo '客户端断开连接:' . $request;
    unset($GLOBALS['fd'][$request]);
});

$ws->start();

/**
 * 客户端：
 * 引入jquery . js、webSocket . js。
 * var msg = document . getElementById('msg');
 * var wsSwever = 'ws://192.168.10.1:9502';
 * var websocket = new WebSocket(wsServer);
 * websocket . onopen = function (evt){
 * 　　//显示登录服务器成功
 * 　　//msg.innerHTML = websocket.readState;
 * 　　//websocket.readState属性：
 * 　　//CONNECTING 0 The connection is not yet open.
 * 　　//OPEN 1 The connection is open and ready to communite.
 * 　　//CLOSEING 2 The connection is in the process of closing。
 * 　　//CLOSED 3 The connection is closed or couldn't be opened.
 * }
 *
 * websocket . onmessage = function (evt){
 * 　　msg . innerHTML += evt . data + '<br>';//不断递增的数据
 * 　　console . log('从服务器获取到的数据：' + evt . data);
 * };
 * //监听连接关闭
 * websocket . onclose = function (evt){
 * 　　console . log('服务器拒绝');
 * };
 * //监听连接错误信息
 * websocket . onerror = function (evt){
 * 　　console . log('错误：' . evt . data);
 * }
 *
 * //发送信息
 * function send_msg()
 * {
 * 　　var text = document . getElementById('text') . value;//获取数据
 * 　　websocket . send(text);
 * 　　document . getElementById('text') . value = '';
 * }
 *
 * //发送昵称
 * function send_name()
 * {
 * 　　var text = document . getElementById('text') . value;//获取数据
 * 　　websocket . send("#name#" + text);//向服务器发送数据
 * 　　document . getElementById('text') . value = '';
 * 　　var myTitle = document . getElementById("myTitle");
 * 　　myTitle . innerHtml = "IM " + text;
 * 　　alert("设置成功");
 * }
 */


